package com.solome.util;

import java.lang.annotation.Annotation;

import com.badlogic.gdx.utils.Array;
import com.solome.core.ManageObject;
import com.solome.core.instr.SECOND;

public class InvokeFactory {

	private static InvokeFactory instance = null;// new InvokeFactory();

	public static synchronized InvokeFactory getInstance() {
		if (instance == null) {
			instance = new InvokeFactory();
		}
		return instance;
	}

	public static abstract class Invokable {

		/** 对象创建时间 */
		protected long createTime;

		/** 上次更新时间 */
		protected long lastUpdateTime;

		/**
		 * 触发操作
		 * 
		 */
		public abstract void invoke() throws Exception;

		public long getCreateTime() {
			return createTime;
		}

		public void setCreateTime(long createTime) {
			this.createTime = createTime;
		}

		public long getLastUpdateTime() {
			return lastUpdateTime;
		}

		public void setLastUpdateTime(long lastUpdateTime) {
			this.lastUpdateTime = lastUpdateTime;
		}
	}

	private Array<Invokable> array = new Array<Invokable>();

	public void addInvok(Invokable invokable) {
		array.add(invokable);
	}

	public void invoke() {
		for (Invokable invoke : array) {
			try {
				this.action(invoke);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 执行
	 * 
	 * @param invoke
	 * @throws Exception
	 */
	private void action(Invokable invoke) throws Exception {
		Annotation tmp = invoke.getClass().getAnnotation(SECOND.class);
		if (tmp == null) {
			invoke.invoke();
			return;
		}

		SECOND sec = (SECOND) tmp;
		long interval = sec.value() * ManageObject.SECOND;
		Invokable obj = (Invokable) invoke;
		// Method method = null;
		interval = sec.value() * ManageObject.SECOND;
		long now = System.currentTimeMillis();
		long last = obj.getLastUpdateTime();
		if (last <= 0) {
			obj.setLastUpdateTime(now);
			return;
		}
		long delta = now - last;
		if (delta < interval)
			return;

		invoke.invoke();
		obj.setLastUpdateTime(now);
	}

	public void dispose() {
		// TODO Auto-generated method stub
		array.clear();
	}

}
